import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/model/index_data_model.dart';
import 'package:yw_bapp/pages/cash_page.dart';
import 'package:yw_bapp/pages/my_qr.dart';
import 'package:yw_bapp/pages/recommended_menu_list.dart';
import 'package:yw_bapp/pages/store_info_set.dart';
import 'package:yw_bapp/provider/manager_info_provider.dart';
import 'package:yw_bapp/provider/role_info_provider.dart';
import 'package:yw_bapp/provider/store_info_provider.dart';
import 'package:yw_bapp/utils/show_tip_pop.dart';
import 'package:yw_bapp/utils/timeHandle.dart';
import 'package:yw_bapp/widgets/custom_route_widget.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/no_data_widget.dart';
import 'package:yw_bapp/widgets/order_item_widget.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:provider/provider.dart';
import 'package:yw_bapp/widgets/text_image_widget.dart';
import 'package:yw_bapp/widgets/top_image_text.dart';
import 'package:yw_bapp/widgets/wrap_gesture_widget.dart';
import 'more_order_list.dart';

class MyStore extends StatefulWidget {
  @override
  _MyStoreState createState() => _MyStoreState();
}

class _MyStoreState extends State<MyStore> {
  EasyRefreshController _controller;
  List<TodayOrderList> todyList;
  // 今日收入
  int todyIncome = 0;
  // 账户余额
  int totalAccount = 0;
  // 今日收入几笔
  int todayOrderNumer = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getIndexData(context);

    _controller = EasyRefreshController();
  }

  @override
  Widget build(BuildContext context) {
    // 门店信息
    final storeInfo = context.watch<StoreInfoProvider>().storeInfo ?? null;
    // 登录者信息
    final managerInfo =
        context.watch<ManagerInfoProvider>().managerInfo ?? null;
    // 角色信息
    final roleInfo =
        context.watch<RoleInfoProvider>().roleInfo?.withdrawStruct ?? null;

    return Scaffold(
        appBar: XAppBar(
          statusBarColor: ColorUtil.color('#FFC49226'),
          bgColor: ColorUtil.color('#FFC49226'),
          title: "我的门店",
          icon: null,
          fun: () {},
        ),
        body: EasyRefresh.custom(
          enableControlFinishRefresh: false,
          enableControlFinishLoad: true,
          controller: _controller,
          header: BezierCircleHeader(
              color: ColorUtil.color("#FFFF7200"),
              backgroundColor: ColorUtil.color("#FFFFFFFF")),
          footer: BezierBounceFooter(
              color: ColorUtil.color("#FFFF7200"),
              backgroundColor: ColorUtil.color("#FFFFFFFF")),
          onRefresh: () async {
            await Future.delayed(Duration(seconds: 2), () {
              _getIndexData(context);
              _controller.resetLoadState();
            });
          },
          onLoad: () async {
            await Future.delayed(Duration(seconds: 2), () {
              _getIndexData(context);
              _controller.finishLoad(noMore: true);
            });
          },
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  return Container(
                    padding: EdgeInsets.fromLTRB(15, 20, 15, 0),
                    child: Column(
                      children: [
                        // 欢迎行
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              width: 140,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  // 头像
                                  CircleAvatar(
                                    backgroundImage:
                                        "${storeInfo?.logoPic ?? ''}" != ''
                                            ? NetworkImage(
                                                "${storeInfo?.logoPic}",
                                              )
                                            : AssetImage(
                                                'images/defaultLogo.png',
                                              ),
                                    radius: 20,
                                  ),
                                  //
                                  LimitedBox(
                                    maxWidth: 90,
                                    child: Text(
                                      "欢迎你，${managerInfo?.name ?? '登录者信息'}",
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: 15,
                                          color: ColorUtil.color("#FF333333"),
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            wrapGesture(
                                child: Container(
                              width: 149,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  LimitedBox(
                                    maxWidth: 100,
                                    child: Text(
                                      "${storeInfo?.brandName ?? ''}(${storeInfo?.shopName ?? ''})",
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: ColorUtil.color("#FF333333"),
                                      ),
                                    ),
                                  ),
                                  Icon(Icons.navigate_next,
                                      color: ColorUtil.color("#FF999999"))
                                ],
                              ),
                            ))
                          ],
                        ),
                        // 卡片行
                        cardIndex(context),
                        // 设置行
                        settingsRow(context),
                        // 订单行
                        orderContainer(context)
                      ],
                    ),
                  );
                },
                childCount: 1,
              ),
            ),
          ],
        ));
  }

  // 获取首页数据
  _getIndexData(BuildContext context) {
    CommonDao.GetIndexData().then((IndexDataModel model) => {
          if (model.status == 200)
            {
              // 存今日订单
              todyList = model.data.todayOrderList,
              // 存门店信息
              context
                  .read<StoreInfoProvider>()
                  .setStoreInfo(model.data.storeInfo),
              // 存登录者信息
              context
                  .read<ManagerInfoProvider>()
                  .setManagerInfo(model.data.managerInfo),
              // 存登录者的角色信息
              context.read<RoleInfoProvider>().setRoleInfo(model.data.roleInfo),
              setState(() {
                todyIncome = model.data.centTodayIncome;
                totalAccount = model.data.centTotalAccount;
                todayOrderNumer = model.data.todayOrderNumer;
                // 将店铺的账户余额存起来
                context.read<StoreInfoProvider>().setStoreBalance(totalAccount);
              })
            },
          // LoadingPop.hide(context)
        });
  }

  // 卡片区域
  Widget cardIndex(BuildContext context) {
    return Card(
      margin: EdgeInsets.only(top: 23),
      color: Colors.blueAccent,
      //z轴的高度，设置card的阴影
      elevation: 20.0,
      //设置shape，这里设置成了R角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(5.0)),
      ),
      //对Widget截取的行为，比如这里 Clip.antiAlias 指抗锯齿
      clipBehavior: Clip.antiAlias,
      semanticContainer: false,
      child: Container(
        height: 108,
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
            image: new DecorationImage(
                image: new AssetImage('images/indexCardBg.png'),
                fit: BoxFit.cover)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 标题
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: TextWithImage(
                    title: '今日收入${todayOrderNumer}笔',
                    imageUrl: 'images/question.png',
                    func: () {
                      showAlertDialog(
                        context,
                        '平台用于方便结算的符号',
                        title: '关于开心豆',
                        confirmText: '知道啦',
                        onlyConfirm: true,
                      );
                    },
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: TextWithImage(title: '账户余额', imageUrl: ''),
                ),
              ],
            ),
            // 金额
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Expanded(
                  flex: 1,
                  child: TextWithImage(
                    title: '${todyIncome / 100}',
                    imageUrl: 'images/bean_white.png',
                    textStyle: TextStyle(fontSize: 21),
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: TextWithImage(
                    title: '${totalAccount / 100}',
                    imageUrl: 'images/bean_white.png',
                    textStyle: TextStyle(fontSize: 21),
                  ),
                )
              ],
            ),
            // 按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MBtn(
                  borderColor: Colors.white,
                  function: () {
                    Navigator.of(context).push(CustomRoute(MoreOrderList(), 5));
                    LoadingPop.show(context);
                  },
                  title: '查看明细',
                  btnWidth: 76,
                  btnHeight: 26,
                  // textColor: Colors.white,
                  textStyle: TextStyle(fontSize: 12),
                ),
                MBtn(
                  borderColor: Colors.white,
                  function: () {
                    Navigator.of(context).push(CustomRoute(CashPage(), 5));
                    LoadingPop.show(context);
                  },
                  title: '兑现',
                  btnWidth: 76,
                  btnHeight: 26,
                  // textColor: Colors.white,
                  textStyle: TextStyle(fontSize: 12),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  //  设置区域
  Widget settingsRow(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 24),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 1,
            child: TopImageWithText(
              title: '门店信息设置',
              imageUrl: 'images/storeInfoSet.png',
              func: () {
                Navigator.of(context).push(CustomRoute(StoreInfoSet(), 5));
                // LoadingPop.show(context);
              },
            ),
          ),
          Expanded(
            flex: 1,
            child: TopImageWithText(
              title: '员工设置',
              imageUrl: 'images/staffSet.png',
            ),
          ),
          Expanded(
            flex: 1,
            child: TopImageWithText(
              title: '我的收款码',
              imageUrl: 'images/qrSet.png',
              func: () {
                Navigator.of(context).push(CustomRoute(QrCode(), 5));
                LoadingPop.show(context);
              },
            ),
          ),
          Expanded(
            flex: 1,
            child: TopImageWithText(
              title: '推荐菜品设置',
              imageUrl: 'images/menuSet.png',
               func: () {
                Navigator.of(context).push(CustomRoute(RecommendedMenu(), 5));
                // LoadingPop.show(context);
              }
            ),
          )
        ],
      ),
    );
  }

  //  今日订单区域
  Widget orderContainer(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '今日订单',
                style: TextStyle(
                    color: ColorUtil.color("#FF333333"),
                    fontSize: 18,
                    fontWeight: FontWeight.bold),
              ),
              Container(
                child: wrapGesture(
                  function: () {
                    Navigator.of(context).push(CustomRoute(MoreOrderList(), 4));
                    LoadingPop.show(context);
                  },
                  child: Row(
                    children: [
                      Text('更多',
                          style: TextStyle(
                              fontSize: 12,
                              color: ColorUtil.color("#FF999999"))),
                      Icon(
                        Icons.navigate_next,
                        color: ColorUtil.color("#FF999999"),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
          Container(
              height: 338,
              margin: EdgeInsets.only(top: 12),
              child: todyList?.length != 0 ?? false
                  ? ListView.builder(
                      itemCount: todyList?.length ?? 0,
                      itemBuilder: (BuildContext context, int index) {
                        return OrderItem(
                          orderNum: todyList[index].innerOrderId,
                          centScorePrice: todyList[index].centPayScorePrice,
                          timeSamp: DateUtils.instance
                              .GLDataExchange(todyList[index].createdAt,
                                  format: 'yyy/MM/dd  HH:mm:ss')
                              .toString(),
                        );
                      },
                    )
                  : NoData()),
        ],
      ),
    );
  }
}
